package com.xyzwps.paimon.furina.modules.post.service

import com.xyzwps.paimon.furina.common.AppErrorCode.*
import com.xyzwps.paimon.furina.common.AppException
import com.xyzwps.paimon.furina.common.DateTimeUtil
import com.xyzwps.paimon.furina.common.DeleteOption
import com.xyzwps.paimon.furina.common.DeleteOption.*
import com.xyzwps.paimon.furina.modules.post.entity.PostCollection
import com.xyzwps.paimon.furina.modules.post.entity.PostCollectionRepository
import org.springframework.stereotype.Service

@Service
class PostCollectionService(private val collectionRepository: PostCollectionRepository) {

    fun create(userId: Long, title: String): PostCollection {
        return collectionRepository.create(userId, title)
    }

    fun update(id: Long, userId: Long, title: String): PostCollection {
        val c = findById(id, userId)
            ?: throw AppException(POST_COLLECTION_NOT_FOUND)

        val newC = c.copy(title = title, updateTime = DateTimeUtil.currentLocalDateTime())
        collectionRepository.update(newC)
        return newC
    }

    /**
     * @return true if collection was deleted; false if no collection matched
     */
    fun delete(id: Long, userId: Long): Boolean {
        val c = findById(id, userId) ?: return false

        val now = DateTimeUtil.currentLocalDateTime()
        val newC = c.copy(deleteTime = now, updateTime = now)
        collectionRepository.update(newC)
        return true
    }

    fun findById(id: Long, userId: Long): PostCollection? = this.findById(id)?.takeIf { it.userId == userId }

    fun findById(id: Long): PostCollection? = collectionRepository.findById(id)

    fun findByUserId(userId: Long, option: DeleteOption = UNDELETED_ONLY): List<PostCollection> {
        return collectionRepository.findByUserId(userId, option)
    }
}